import {
  api
} from '@/api'
import router from '@/router'
import Layout from '@/components/layout'
const _import = require('../../router/_import_' + process.env.NODE_ENV)
const state = {
  promptData: '',
  isFirst: true,
  isAuth: false,
  isW7: false,
  isShowPrompt: false, // 是否显示到期提醒
  systemCopyInfo: '', // 获取微擎系统版本信息
  tabbar: {}, // 小程序tabbar设置
  routes: [],
  logo: 'https://lbqny.migugu.com/admin/diy/default.png',
  isFreeAuth: -1, // 是否已授权免费版本
  // 163791
  // 餐饮门店  restaurant
  // 短视频   shortvideo
  // 门店  radarstore
  // 装修  decorate
  // 名片  card
  app_model_name: 'longbing_card', // 发布版本
  accountLevel: 0, // 账号角色（0管理员；1员工）
  diyID: 0,
  diyKey: 0,
  isSaasAuth: false, // 是否是saas授权
  isPayclassTab: 'course'
}
const getters = {
  isAuth: state => {
    return state.isAuth
  },
  isW7: state => {
    return state.isW7
  },
  routes: state => {
    return state.routes
  }
}
const mutations = {
  // 修改到期提醒数据
  changePromptData (state, item) {
    let { status } = item
    if (status === 2) {
      state.isShowPrompt = true
    } else if (status === 1 && state.isFirst) {
      state.isFirst = false
      state.isShowPrompt = true
    }
    state.promptData = item
  },
  // 修改是否显示到期提醒
  changeIsShowPrompt (state, item) {
    state.isShowPrompt = item
  },
  changeRoutesItem (state, item) {
    console.log('changeItem ==>', item)
    let { key, val } = item
    state[key] = val
  },
  saveRoutes (state, item = []) {
    state.routes = item
    state.isAuth = true
  }
}
const actions = {
  isWeiVersion ({ commit }, obj) {
    let data = {key: 'isW7', val: obj}
    commit('changeRoutesItem', data)
  },
  getUserPromission ({
    commit
  }, obj) {
    if (process.env.NODE_ENV === 'development') {
      commit('saveRoutes', obj.routes)
      routerGo(obj.routes, obj)
    } else {
    // 正式请求接口获取路由
      api.returnAdmin().then(res => {
        if (res.code === 200) {
          let { app_model_name: appModelName, copyright, checkAuth, permission, w7tmp } = res.data
          commit('changeRoutesItem', { key: 'app_model_name', val: appModelName })
          commit('changeRoutesItem', { key: 'isFreeAuth', val: checkAuth === 0 })
          commit('changeRoutesItem', { key: 'logo', val: copyright })
          commit('changeRoutesItem', { key: 'systemCopyInfo', val: w7tmp })

          let allRoutes = [...permission, {
            path: '*',
            redirect: '/404',
            hidden: true
          }]
          commit('saveRoutes', allRoutes)
          routerGo(allRoutes, obj)
        }
      })
    }
  }
}

export default {
  state,
  getters,
  mutations,
  actions
}

function routerGo (routes, obj) {
  let getRouter = filterAsyncRouter(routes) // 过滤路由
  router.options.routes.push(...getRouter)
  router.addRoutes(getRouter) // 动态添加路由
  // localStorage.setItem('routes', JSON.stringify(getRouter))
  obj.next({
    ...obj.to,
    replace: true
  })
}

function filterAsyncRouter (asyncRouterMap) { // 遍历后台传来的路由字符串，转换为组件对象
  const accessedRouters = asyncRouterMap.filter(route => {
    if (route.component) {
      if (route.component === 'Layout') { // Layout组件特殊处理
        route.component = Layout
      } else {
        route.component = _import(route.component)
      }
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })
  return accessedRouters
}

// function getRouteChildre (routes, name) {
//   let routeObj = ''
//   for (let i = 0, len = routes.length; i < len; i++) {
//     if (routes[i].path === name) {
//       routeObj = routes[i]
//       break
//     }
//   }
//   return routeObj
// }
